#include "common.h"

BOOL_E WATT_Init(void)
{
    uart3_init(9600);
    return TRUE;
}

BOOL_E WATT_Read(void)
{
    u8 *revBuf;
    u8 revLen = 5 + 9 * 2;
    u8 ActLen = 0;

    Modbus_Func03_Sync(0x01, 0x0100, 9);
    u16 timeout = 500;
    while (timeout > 0)
    {
        revBuf = Modbus_Get_Rev();
        if (revBuf != NULL)
        {
			//printf("rev:");
            ActLen = Modbus_Get_ReLen();
            // for (int i = 0; i < ActLen; ++i)
            //         printf("%02X ", revBuf[i]);
            //     printf("\r\n");
            if (revLen == ActLen)
            {
                g_A_VOLT = revBuf[3] * 256+ revBuf[4];
                g_B_VOLT = revBuf[5] * 256+ revBuf[6];
                g_C_VOLT = revBuf[7] * 256+ revBuf[8];
                g_A_CURR = revBuf[9] * 256+ revBuf[10];
                g_B_CURR = revBuf[11] * 256+ revBuf[12];
                g_C_CURR = revBuf[13] * 256+ revBuf[14];
                g_A_PWR = revBuf[15] * 256+ revBuf[16];
                g_B_PWR = revBuf[17] * 256+ revBuf[18];
                g_C_PWR = revBuf[19] * 256+ revBuf[20];
                return TRUE;
            }
            else
            {
                Modbus_Clear_Rev();
            }
        }
        timeout--;
        delay_ms(1);
    }
    //printf("watt no response\r\n");
    return FALSE;
}
